package com.lr;

import com.lr.mapper.UserInfoMapper;
import com.lr.pojo.UserInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author bin
 * @date 2025 - 04 -02
 **/
public class Application {
    public static void main(String[] args) throws Exception {

        //getAllUserInfo();获取所有用户信息
//        updateUserNameById("bin", 1L); //更新用户名
//        insertUserInfo();//新增用户信息

//        DeleteUserInfoById();//删除用户信息
    }

    private static void DeleteUserInfoById() throws Exception {
        SqlSession sqlSession = getSqlSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        Integer i = mapper.deleteUserById(3L);
        sqlSession.commit();
        sqlSession.close();
        System.out.println(i);
    }

    private static void insertUserInfo() throws Exception {
        SqlSession sqlSession = getSqlSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("ls");
        userInfo.setUserPassword("123456");
        mapper.inserUserInfo(userInfo);
        sqlSession.commit();
        sqlSession.close();
    }

    private static void updateUserNameById(String name, Long id) throws Exception {
        SqlSession sqlSession = getSqlSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        Integer bin = mapper.UpdateUserNameById(name,id);
        sqlSession.commit();
        sqlSession.close();
    }

    private static void getAllUserInfo() throws Exception {
        SqlSession sqlSession = getSqlSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        List<UserInfo> userInfos = mapper.selectAllUsers();
        userInfos.forEach(System.out::println);
        sqlSession.close();
    }

    public static SqlSession getSqlSession() throws Exception{
        //mybatis的配置环境 通常包含数据库连接信息、映射器配置内容
        String resource = "mybatis-config.xml";
        //使用该方法加载配置文件，返回一个输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //构建SqlSessionFactory对象，它有数据源和其他的配置信息，主要用于创建SqlSession
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //创建SqlSession对象，SqlSession对象用于执行SQL，获取映射器，管理事务
        return sqlSessionFactory.openSession();
    }
    public static void getMySql() throws Exception {
        SqlSession sqlSession = getSqlSession();
        //执行SQL语句，返回一条查询结果
        UserInfo user = sqlSession.selectOne("selectUser", 1);
        System.out.println(user);
        sqlSession.close();
    }
}
